import 'package:get/get.dart';
import 'package:azring/core/repository/default_api.dart';
import 'message_center_state.dart';

class MessageCenterLogic extends GetxController {
  final state = MessageCenterState();
  final _api = DefaultApi();

  /// 格式化时间为相对时间
  String _formatRelativeTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '';
    
    try {
      final time = DateTime.parse(timeStr);
      final now = DateTime.now();
      final difference = now.difference(time);

      if (difference.inMinutes < 1) {
        return '刚刚';
      } else if (difference.inMinutes < 60) {
        return '${difference.inMinutes}分钟前';
      } else if (difference.inHours < 24) {
        return '${difference.inHours}小时前';
      } else if (difference.inDays < 7) {
        return '${difference.inDays}天前';
      } else {
        return timeStr.substring(0, 10); // 返回日期部分
      }
    } catch (e) {
      return timeStr;
    }
  }

  @override
  void onInit() {
    super.onInit();
    loadMessages();
  }

  /// 切换Tab
  void changeTab(int index) {
    state.currentTabIndex.value = index;
  }

  /// 加载消息数据
  Future<void> loadMessages() async {
    await Future.wait([
      loadSystemNotifications(),
      loadHealthAlerts(),
      loadFamilyApplications(),
    ]);
  }

  /// 加载系统通知
  Future<void> loadSystemNotifications() async {
    try {
      final response = await _api.queryAppNoticeListGet();
      
      if (response != null && response['code'] == 200) {
        final rows = response['rows'] as List?;
        if (rows != null) {
          state.systemNotifications.value = rows.map((item) {
            final createTime = item['createTime'] ?? '';
            final status = item['status']?.toString() ?? '0';
            final isRead = status == '1';
            
            print('通知: ${item['noticeTitle']}, status: $status, isRead: $isRead');
            
            return {
              'noticeId': item['noticeId'],
              'title': item['noticeTitle'] ?? '系统通知',
              'content': item['noticeContent'] ?? '',
              'time': _formatRelativeTime(createTime),
              'createTime': createTime,
              'noticeType': item['noticeType']?.toString() ?? '1',
              'status': status,
              'isRead': isRead,
            };
          }).toList();

          // 统计未读数量（status == "0"）
          state.systemNotificationCount.value = state.systemNotifications
              .where((item) => item['status'] == '0')
              .length;
          
          print('总通知数: ${state.systemNotifications.length}, 未读数: ${state.systemNotificationCount.value}');
        }
      }
    } catch (e) {
      print('加载系统通知失败: $e');
    }
  }

  /// 加载健康警报
  Future<void> loadHealthAlerts() async {
    try {
      // TODO: 调用健康警报接口
      state.healthAlerts.value = [];

      state.healthAlertCount.value =
          state.healthAlerts.where((item) => item['isRead'] == false).length;
    } catch (e) {
      print('加载健康警报失败: $e');
    }
  }

  /// 加载家庭圈申请
  Future<void> loadFamilyApplications() async {
    try {
      // 并行调用两个接口：我邀请的消息和我申请的消息
      final results = await Future.wait([
        _api.queryInviterMessageListGet(), // 我是邀请人（群主）的消息
        _api.queryApplyMessageListGet(),    // 我是申请人（成员）的消息
      ]);

      final inviterResponse = results[0];
      final applyResponse = results[1];

      final List<Map<String, dynamic>> allApplications = [];

      // 处理我邀请的消息列表（我是群主）
      // joinType = 1 时：我邀请别人，只看状态
      // joinType = 2 时：别人申请加入我的群，我需要审核
      if (inviterResponse != null && inviterResponse['code'] == 200) {
        final rows = inviterResponse['rows'] as List?;
        if (rows != null) {
          allApplications.addAll(rows.map((item) {
            return {
              'id': item['id'],
              'applicantId': item['applicantId'],
              'applicantName': item['applicantName'] ?? '未知用户',
              'groupName': item['groupName'] ?? '未命名群组',
              'groupCreatorId': item['groupCreatorId'],
              'groupCreator': item['groupCreator'],
              'groupCode': item['groupCode'] ?? '',
              'approvalState': item['approvalState']?.toString() ?? '1',
              'applicantTime': item['applicantTime'] ?? '',
              'joinType': item['joinType']?.toString() ?? '2',
              'isCreator': true, // 标记我是群主
            };
          }).toList());
        }
      }

      // 处理我申请的消息列表（我是成员）
      // joinType = 1 时：别人邀请我，我需要审核
      // joinType = 2 时：我申请加入别人的群，只看状态
      if (applyResponse != null && applyResponse['code'] == 200) {
        final rows = applyResponse['rows'] as List?;
        if (rows != null) {
          allApplications.addAll(rows.map((item) {
            return {
              'id': item['id'],
              'applicantId': item['applicantId'],
              'applicantName': item['applicantName'] ?? '未知用户',
              'groupName': item['groupName'] ?? '未命名群组',
              'groupCreatorId': item['groupCreatorId'],
              'groupCreator': item['groupCreator'],
              'groupCode': item['groupCode'] ?? '',
              'approvalState': item['approvalState']?.toString() ?? '1',
              'applicantTime': item['applicantTime'] ?? '',
              'joinType': item['joinType']?.toString() ?? '1',
              'isCreator': false, // 标记我是成员
            };
          }).toList());
        }
      }

      // 按时间排序（最新的在前）
      allApplications.sort((a, b) {
        final timeA = a['applicantTime'] ?? '';
        final timeB = b['applicantTime'] ?? '';
        return timeB.compareTo(timeA);
      });

      state.familyApplications.value = allApplications;

      // 统计待审批数量（approvalState == "1"）
      state.familyApplicationCount.value = state.familyApplications
          .where((item) => item['approvalState'] == '1')
          .length;
    } catch (e) {
      print('加载家庭圈申请失败: $e');
    }
  }

  /// 查看通知详情（会自动标记为已读）
  Future<Map<String, dynamic>?> viewNotificationDetail(int noticeId) async {
    try {
      final response = await _api.queryAppNoticeGet(noticeId: noticeId);
      
      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          // 刷新列表以更新已读状态
          await loadSystemNotifications();
          
          return {
            'noticeId': data['noticeId'],
            'title': data['noticeTitle'] ?? '系统通知',
            'content': data['noticeContent'] ?? '',
            'createTime': data['createTime'] ?? '',
            'noticeType': data['noticeType']?.toString() ?? '1',
            'status': data['status']?.toString() ?? '0',
            'recordDate': data['recordDate'] ?? '',
          };
        }
      }
      return null;
    } catch (e) {
      print('查看通知详情失败: $e');
      return null;
    }
  }

  /// 刷新数据
  @override
  Future<void> refresh() async {
    await loadMessages();
  }
}
